import { getToken, setToken, removeToken } from '@/utils/auth'
import { loginAPI } from '@/api/user'
import { TOKEN_KEY } from '@/constants/KEY'
export default {
  namespaced: true,
  // 放置状态
  state: () => {
    return {
      token: getToken || '' // 获取token
    }
  },
  mutations: {
    // 修改token
    setToken (state, token) {
      state.token = token // 设置token
      setToken(token) // 缓存到浏览器
    },
    // 清除token
    clearuserinfo (state) {
      state.token = ''
      removeToken(TOKEN_KEY)
    }
  },
  actions: {
    async login (context, { username, password }) {
      // 调用接口
      const res = await loginAPI({ username, password })
      // 保存token
      context.commit('setToken', res.data.token)
    }
  }
}
